package com.apes.scm.masterdata.enumeration.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.model.EnumerationType;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("enumerationService")
public class EnumerationService extends DomainService {

    @Autowired
    EnumerationRepository enumerationRepository;
    @Autowired
    EnumerationTypeRepository enumerationTypeRepository;

    public EnumerationType save(SimpleRequest request) {
        EnumerationType enumType = request.getO(EnumerationType.class);
        if (enumType.isSysInner()) throw new RuntimeException("系统内定标记不允许修改。");
        return insert(enumType);
    }

    public EnumerationType insert(EnumerationType enumType){
        return enumerationTypeRepository.saveAndFlush(enumType);
    }

    public EnumerationType annotationSave(EnumerationType enumType){
        EnumerationType oldEnumeration = enumerationTypeRepository.findOne(enumType.getId());
        enumType.setVersion( oldEnumeration.getVersion() );
        return insert(enumType);
    }

    /**
     * 功能：用于查找以及查询使用
     *
     * @param request
     * @param request
     * @return
     */
    public Page<EnumerationType> findAllEnumType(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return enumerationTypeRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    /**
     * 功能：查询所有的枚举类型
     *
     * @param request
     * @return
     */
    public Page<EnumerationType> findEnumType(SimpleRequest request) {
        return enumerationTypeRepository.find(request.get("key"), PageRequest.of(request.get("page"), request.get("size")));
    }

    public Page<Enumeration> findByType(String type, SimpleRequest request) {
        EnumerationType enumerationType = enumerationTypeRepository.findOne(type);
        return enumerationRepository.findByType(enumerationType, PageRequest.of(request.get("page"), request.get("size")));
    }

    public Page<Enumeration> findEnumerationByType(SimpleRequest request) {
        String key = request.get("key");
        EnumerationType enumerationType = enumerationTypeRepository.findOne(key);
        if (enumerationType == null) {
            throw new RuntimeException("系统中找不到" + key + "类型");
        }
        return enumerationRepository.findByTypeAndValidIsTrue(enumerationType,
                PageRequest.of(request.get("page"), request.get("size"), new Sort(Sort.Direction.ASC, "code")));
    }

    /**
     *  应聘表多选需要默认值false
     *  专用接口
     * @param request
     * @return
     */
    public List findEnumerationByType2(SimpleRequest request) {
        String key = request.get("key");
        EnumerationType enumerationType = enumerationTypeRepository.findOne(key);
        if (enumerationType == null) {
            throw new RuntimeException("系统中找不到" + key + "类型");
        }
        List result = new ArrayList();
        Page<Enumeration> enumerationPage = enumerationRepository.findByTypeAndValidIsTrue(enumerationType,
                PageRequest.of(request.get("page"), request.get("size"), new Sort(Sort.Direction.ASC, "code")));
        if(enumerationPage!=null){
            enumerationPage.forEach(enumeration -> {
                Map m = new HashMap();
                m.put("Enumeration",enumeration.getDescription());
                m.put("state", false);
                result.add(m);
            });
        }

        return result;
    }

    /**
     * 查询具体的枚举值
     */
    public Enumeration findByID(SimpleRequest request) {
        String id = request.get("id");
        return enumerationRepository.findOne(id);
    }

    public Enumeration findByTypeAndDescription(SimpleRequest request) {
        String type = request.get("type");
        String description = request.get("description");
        return enumerationRepository.findByTypeAndValue(description,type);
    }

    /**
     * 传入枚举编码，查询具体枚举
     *
     * @param id
     * @return
     */
    public Enumeration findById(String id) {
        return enumerationRepository.findOne(id);
    }
    /*
     *  查询在岗状态
     * */
    public Page<Enumeration> findOnDutyState(SimpleRequest request) {
        return findByType("onDutyState", request);
    }

    public Enumeration findByDescriAnaTypeOrCreate(String descri,String type){
        Enumeration enumeration = enumerationRepository.findByTypeAndValue(descri,type);
        if(enumeration == null){
            EnumerationType enumerationType = enumerationTypeRepository.findOne(type);
            if(enumerationType!=null){
                enumeration = new Enumeration();
                enumeration.setType(enumerationType);
                enumeration.setDescription(descri);
                enumeration.setValid(true);
                enumerationRepository.saveAndFlush(enumeration);
            }
        }
        return enumeration;
    }

    /**
     * 获取对账单状态
     * @param request
     * @return
     */
    public JSONObject queryStatementState(SimpleRequest request){
        Page<Enumeration> statementStates = findByType("statementState", request);
        //枚举定义的时候根据备注内容排序
        List<Enumeration> content = statementStates.getContent().stream().sorted(Comparator.comparing(Enumeration::getRemark)).collect(Collectors.toList());
        JSONArray filters = request.getJO().getJSONObject("group").getJSONArray("filters");
        if (!filters.isEmpty()){
            String value = filters.getJSONObject(0).getString("value");
            //商家端不展示创建状态
            if ("merchantSystem".equals(value)){
                content.remove(0);
            }
        }
        List<Map<String,Object>> maps = new ArrayList<>();
        content.forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id",item.getCode());
            map.put("name",item.getDescription());
            maps.add(map);
        });
        JSONObject result = new JSONObject();
        result.put("content",maps);
        result.put("page",request.get("page"));
        result.put("size",request.get("size"));
        return result;
    }

}
